
package com.jf.cloud.service.sysmanager.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jf.cloud.service.sysmanager.common.base.BaseService;
import com.jf.cloud.service.sysmanager.common.base.GenericsUtils;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.Condition;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.db.jdbc.RowMapperFactory;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.ObjectUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.MatchConstant;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.TradeType;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgFinanceFlowDetailService;
import com.jf.cloud.service.sysmanager.dao.IPubgMatchSettlementService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserMatchService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserTeamService;
import com.jf.cloud.service.sysmanager.entity.PubgClub;
import com.jf.cloud.service.sysmanager.entity.PubgFinanceFlowDetail;
import com.jf.cloud.service.sysmanager.entity.PubgMatch;
import com.jf.cloud.service.sysmanager.entity.PubgMatchSettlement;
import com.jf.cloud.service.sysmanager.entity.PubgTeam;
import com.jf.cloud.service.sysmanager.entity.PubgUser;
import com.jf.cloud.service.sysmanager.entity.PubgUserClub;
import com.jf.cloud.service.sysmanager.entity.PubgUserMatch;
import com.jf.cloud.service.sysmanager.entity.PubgUserTeam;


/**
 * 员工服务实现
 * 
 * @author 绝峰代码机1.0 创建时间：2018-03-31
 */
@Service("pubgClubService")
public class PubgClubServiceImpl extends BaseService<PubgClub, Long> implements IPubgClubService {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PubgClubServiceImpl.class);

	/**
	 * JPA公共DAO
	 */
	@Resource
	private BaseDao baseDao;

	private RowMapper<PubgClub> rowMapper = new BeanPropertyRowMapper<PubgClub>(GenericsUtils.getSuperClassGenricType(this.getClass()));

	/**
	 * 员工服务
	 */
	@Resource
	private IPubgUserService pubgUserService;

	@Resource
	private IPubgUserClubService pubgUserClubService;

	@Resource
	private IPubgUserTeamService pubgUserTeamService;
	
	@Resource
	private IPubgUserMatchService pubgUserMatchService;
	
	@Resource
	private IPubgMatchSettlementService pubgMatchSettlementService;
	
	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;

	/**
	 * 根据主键查询员工
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public PubgClub findPubgClub(Long rowId) throws Exception {
		try {
			return this.baseDao.findObject("", rowMapper, rowId);
		} catch (Exception e) {
			throw new Exception("根据主键查询员工出错！", e);
		}
	}

	/**
	 * 根据查询条件获取员工列表
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public List<PubgClub> findPubgClubList(Condition qc) throws Exception {
		try {
			String sql = "SELECT ROW_ID, CLUB_NO, CLUB_NAME, CLUB_PHOTO, MINISTER_ID, MINISTER_NAME, INVITE_CODE, CLUB_INTRO, EXCHAGE_RATIO, CLUB_BALANCE, RECHARGE_SUM, OPT_ID, OPT_ACCOUNT, OPT_TIME FROM pubg_club";
			return this.baseDao.findList(sql, rowMapper);
		} catch (Exception e) {
			throw new Exception("根据查询条件获取员工列表出错！", e);
		}
	}

	/**
	 * 新增/修改俱乐部
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	@Transactional
	public PubgClub saveOrUpdatePubgClub(PubgClub pubgClub) throws Exception {
		try {
		    StringBuilder ministerIdArray = new StringBuilder();//记录设置的管理员ROW_ID
            StringBuilder ministerNameArray = new StringBuilder();//记录设置的管理员帐号
			if (pubgClub != null && StringUtil.isNotEmpty(pubgClub.getMinisterName())) {
				String[] userAccountList = pubgClub.getMinisterName().split(",");
				for (String userAccount:userAccountList) {
					Query query = new Query();
					query.put("USER_ACCOUNT", userAccount);
					PubgUser pubgUser = pubgUserService.find(query);
					if (pubgUser != null && pubgUser.getUserRole() == 10 && (pubgUser.getBalance() == null || pubgUser.getBalance() == 0)) {
						query = new Query();
						query.put("USER_ID", pubgUser.getRowId());
						query.put("_NOT_EQUAL$RELATION_STATE", PubgConstant.USER_CLUB_RELATION_STATE_4);
						List<PubgUserClub> userClubList = pubgUserClubService.findList(query);//俱乐部关系
						if (userClubList == null || userClubList.size() == 0) {
							query = new Query();
							query.put("USER_ID", pubgUser.getRowId());
							query.put("_NOT_EQUAL$RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_4);
							List<PubgUserTeam> userTeamList = pubgUserTeamService.findList(query);//战队关系
							if (userTeamList == null || userTeamList.size() == 0) {
								pubgUserService.update("UPDATE pubg_user SET USER_ROLE = 30 WHERE ROW_ID = ? ", new Object[]{pubgUser.getRowId()});
                                ministerIdArray.append(pubgUser.getRowId() + ",");
                                ministerNameArray.append(pubgUser.getUserAccount() + ",");
							}
						}
					}
				}
			}
            pubgClub.setMinisterId(ministerIdArray.toString());//设置管理员ROW_ID
			pubgClub.setMinisterName(ministerNameArray.toString());//为了方便like查询，必须在结尾加上逗号
			return this.baseDao.saveAll(pubgClub);
		} catch (Exception e) {
			throw new RuntimeException("新增/修改俱乐部出错！", e);
		}
	}

	/**
	 * 更新俱乐部信息
	 *
	 * @author 代码机1.0 创建时间：2018-03-31
	 */
    @Transactional
	public void updatePubgClub(PubgClub pubgClub) throws Exception {
		try {
            //修改时,先将原俱乐部管理员还原成普通用户 BEGIN
            PubgClub oldPubgClub = findByPK(pubgClub.getRowId());
            String oldMinisterName = oldPubgClub.getMinisterName();
            if (StringUtil.isNotEmpty(oldMinisterName)) {
                String[] oldMinisterNameArray = oldMinisterName.split(",");
                for (String userAccount:oldMinisterNameArray) {
                    Query query = new Query();
                    query.put("USER_ACCOUNT", userAccount);
                    PubgUser pubgUser = pubgUserService.find(query);
                    if (pubgUser != null && pubgUser.getUserRole() == 30) {
                        pubgUserService.update("UPDATE pubg_user SET USER_ROLE = 10 WHERE ROW_ID = ? ", new Object[]{pubgUser.getRowId()});
                    }
                }
            }
            //修改时,先将原俱乐部管理员还原成普通用户 END

            StringBuilder ministerIdArray = new StringBuilder();//记录设置的管理员ROW_ID
            StringBuilder ministerNameArray = new StringBuilder();//记录设置的管理员帐号
			if (pubgClub != null && StringUtil.isNotEmpty(pubgClub.getMinisterName())) {
				String[] userAccountList = pubgClub.getMinisterName().split(",");
				for (String userAccount:userAccountList) {
					Query query = new Query();
					query.put("USER_ACCOUNT", userAccount);
					PubgUser pubgUser = pubgUserService.find(query);
					if (pubgUser != null && pubgUser.getUserRole() == 10 && (pubgUser.getBalance() == null || pubgUser.getBalance() == 0)) {
						query = new Query();
						query.put("USER_ID", pubgUser.getRowId());
						query.put("_NOT_EQUAL$RELATION_STATE", PubgConstant.USER_CLUB_RELATION_STATE_4);
						List<PubgUserClub> userClubList = pubgUserClubService.findList(query);//俱乐部关系
						if (userClubList == null || userClubList.size() == 0) {
							query = new Query();
							query.put("USER_ID", pubgUser.getRowId());
							query.put("_NOT_EQUAL$RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_4);
							List<PubgUserTeam> userTeamList = pubgUserTeamService.findList(query);//战队关系
							if (userTeamList == null || userTeamList.size() == 0) {
								pubgUserService.update("UPDATE pubg_user SET USER_ROLE = 30 WHERE ROW_ID = ? ", new Object[]{pubgUser.getRowId()});
                                ministerIdArray.append(pubgUser.getRowId()+",");
                                ministerNameArray.append(pubgUser.getUserAccount() + ",");
							}
						}
					}
				}
			}

            if (ministerIdArray != null && ministerIdArray.toString().length() > 0 && ministerNameArray != null && ministerNameArray.toString().length() > 0) {
                pubgClub.setMinisterId(ministerIdArray.toString());
                pubgClub.setMinisterName(ministerNameArray.toString());
            } else {
				pubgClub.setMinisterId(null);
				pubgClub.setMinisterName(null);
			}

			StringBuilder updateSql = new StringBuilder("UPDATE pubg_club SET OPT_ID = ?, OPT_ACCOUNT = ?, OPT_TIME = ? ");
			List<Object> params = new ArrayList<Object>();
			params.add(pubgClub.getOptId());
			params.add(pubgClub.getOptAccount());
			params.add(pubgClub.getOptTime());
			if (StringUtil.isNotEmpty(pubgClub.getClubName())) {
				updateSql.append(", CLUB_NAME = ?");
				params.add(pubgClub.getClubName());
			}
            if (StringUtil.isNotEmpty(pubgClub.getMinisterId())) {
                updateSql.append(", MINISTER_ID = ?");
                params.add(pubgClub.getMinisterId());
            }
			if (StringUtil.isNotEmpty(pubgClub.getMinisterName())) {
				updateSql.append(", MINISTER_NAME = ?");
				params.add(pubgClub.getMinisterName() + ",");//为了方便like查询，必须在结尾加上逗号
			}
			if (StringUtil.isNotEmpty(pubgClub.getInviteCode())) {
				updateSql.append(", INVITE_CODE = ?");
				params.add(pubgClub.getInviteCode());
			}
			if (StringUtil.isNotEmpty(pubgClub.getClubIntro())) {
				updateSql.append(", CLUB_INTRO = ?");
				params.add(pubgClub.getClubIntro());
			}
			if (StringUtil.isNotEmpty(pubgClub.getExchageRatio())) {
				updateSql.append(", EXCHAGE_RATIO = ?");
				params.add(pubgClub.getExchageRatio());
			}
			//加鸡蛋时记录到俱乐部余额,注意此处传递的值是变化的鸡蛋数量，不是总量！！！
			if (pubgClub.getClubBalance() != null) {
				updateSql.append(", CLUB_BALANCE = IFNULL(CLUB_BALANCE, 0) + ?");
				params.add(pubgClub.getClubBalance());
			}
			//加鸡蛋时记录到充值总额,注意此处传递的值是增加的鸡蛋数量，不是总量！！！
			if (pubgClub.getRechargeSum() != null && pubgClub.getRechargeSum() > 0) {
				updateSql.append(", RECHARGE_SUM = IFNULL(RECHARGE_SUM, 0) + ?");
				params.add(pubgClub.getRechargeSum());
			}
			updateSql.append(" WHERE ROW_ID=? ");
			params.add(pubgClub.getRowId());
			baseDao.update(updateSql.toString(), params.toArray());
		} catch (Exception e) {
			throw new RuntimeException("更新俱乐部出错！", e);
		}
	}
	
    /**
     * 更新战队余额 并插入流水
     * 
     * @author 朱建文 创建时间：2018年4月4日 下午3:51:58
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
    public void updateTeamBalance(PubgTeam pubgTeam, Integer optType, Double optMoney) throws Exception {
    	StringBuffer sb = new StringBuffer();
    	
    	// 减鸡蛋
    	if (optType == 2) {
			optMoney = optMoney * -1;
		}
    	
    	sb.append(" UPDATE ");
    	sb.append("   pubg_team ");
    	sb.append(" SET ");
    	sb.append("   TEAM_BALANCE = TEAM_BALANCE + ?, ");
    	
    	// 如果是加款需要更新 充值总额？？？？？
    	if (optType == 1) {
    		sb.append("  RECHARGE_SUM = RECHARGE_SUM + " + optMoney + ", ");
		}
    	sb.append(" OPT_ID = ?, OPT_ACCOUNT = ?, OPT_TIME = ? ");
    	sb.append(" WHERE ");
    	sb.append("   ROW_ID = ? AND CLUB_ID = ? AND TEAM_BALANCE = ? ");
    	boolean boo = this.safeUpdate(sb.toString(), 1, 
    			optMoney, pubgTeam.getOptId(), pubgTeam.getOptAccount(), DateUtil.getCurrentDateTime(),
    			pubgTeam.getRowId(), pubgTeam.getClubId(), pubgTeam.getTeamBalance());
    	if (!boo) {
			throw new RuntimeException("更新战队余额失败！");
		}
    	
		// 插入资金流水
    	PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    	pubgFinanceFlowDetail.setClubId(pubgTeam.getClubId());
    	pubgFinanceFlowDetail.setClubName(pubgTeam.getClubName());
    	pubgFinanceFlowDetail.setInOutFlag(optType);
    	pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    	pubgFinanceFlowDetail.setTeamId(pubgTeam.getRowId());
    	pubgFinanceFlowDetail.setTeamName(pubgTeam.getTeamName());
    	pubgFinanceFlowDetail.setTradeMoney(optMoney > 0 ? optMoney : optMoney * -1);
    	pubgFinanceFlowDetail.setTradeMoneyAfter(pubgTeam.getTeamBalance() + optMoney);
    	pubgFinanceFlowDetail.setTradeTypeId(TradeType.EGG_ADD.key());
    	pubgFinanceFlowDetail.setTradeTypeName(TradeType.EGG_ADD.value());
    	if (optType == 2) {
    		pubgFinanceFlowDetail.setTradeTypeId(TradeType.EGG_REDUCE.key());
    		pubgFinanceFlowDetail.setTradeTypeName(TradeType.EGG_REDUCE.value());
		}
    	pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    	log.info("更新战队余额成功！");
    }
    
    /**
     * 更新赛事状态（不包含 已结束）“已结束”需要独立处理
     * 
     * @author 朱建文 创建时间：2018年4月8日 下午4:29:40
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
    public void updateMatchState(PubgMatch pubgMatch, String matchState, PubgUser pubgUser) throws Exception {
    	try {
    		Double applyFeeSum = 0.0;
			String matchStateOld = MatchConstant.MATCH_STATE_10.getId() + "";
			if ((MatchConstant.MATCH_STATE_40.getId() + "").equals(matchState)) {
				matchStateOld = MatchConstant.MATCH_STATE_30.getId() + "";
			} else if ((MatchConstant.MATCH_STATE_50.getId() + "").equals(matchState)) {
				matchStateOld = MatchConstant.MATCH_STATE_40.getId() + "";
				
				// 查询最终报名费
				String sql = "SELECT SUM(APPLY_FEE) FROM pubg_user_match ";
				sql += " WHERE MATCH_ID = ? AND CLUB_ID = ? AND USER_STATE = ? ";
				applyFeeSum = this.baseDao.find(sql, Double.class, 
						pubgMatch.getRowId(), pubgMatch.getClubId(), UserMatchConstant.USER_MATCH_20.getId());
				
			} else if ((MatchConstant.MATCH_STATE_60.getId() + "").equals(matchState)) {
				matchStateOld = MatchConstant.MATCH_STATE_50.getId() + "";
			} else if ((MatchConstant.MATCH_STATE_80.getId() + "").equals(matchState)) {
				matchStateOld = MatchConstant.MATCH_STATE_10.getId() + "," + MatchConstant.MATCH_STATE_30.getId();
			}
			
			// 更新赛事状态
			StringBuffer sb = new StringBuffer();
			sb.append(" UPDATE ");
			sb.append("   pubg_match ");
			sb.append(" SET ");
			sb.append("   MATCH_STATE = ?, OPT_ID = ?, OPT_ACCOUNT = ?, OPT_TIME = ? ");
			
			// 比赛中 需要更新总报名金额
			if ((MatchConstant.MATCH_STATE_50.getId() + "").equals(matchState)) {
				sb.append(", APPLY_SUM_TEMP = " + applyFeeSum);
			}
			
			// 取消赛事 更新取消原因等信息
			if ((MatchConstant.MATCH_STATE_80.getId() + "").equals(matchState)) {
				sb.append(", CANCEL_REASON_ID = " + pubgMatch.getCancelReasonId() + ", ");
				sb.append(" CANCEL_REASON_DESC = '" + pubgMatch.getCancelReasonDesc() + "', ");
				sb.append(" CANCEL_TIME = '" + DateUtil.getCurrentDateTime() + "'");
			}
			sb.append(" WHERE ");
			sb.append("   ROW_ID = ? AND CLUB_ID = ? AND MATCH_STATE IN (" + matchStateOld + ")");
			this.safeUpdate(sb.toString(), 1, matchState, 
					pubgUser.getRowId(), pubgUser.getUserAccount(), DateUtil.getCurrentDateTime(),
					pubgMatch.getRowId(), pubgMatch.getClubId());
			
			// 开始比赛 需要初步计算利润？？？？？？
			if ((MatchConstant.MATCH_STATE_50.getId() + "").equals(matchState)) {
				
			}
			
			// 取消赛事 需要回退 队员的报名费
			if ((MatchConstant.MATCH_STATE_80.getId() + "").equals(matchState)) {
				Query query = new Query();
				query.put("MATCH_ID", pubgMatch.getRowId());
				query.put("CLUB_ID", pubgMatch.getClubId());
				PubgUserTeam pubgUserTeam = null;
				List<PubgUserMatch> userMatchList = this.pubgUserMatchService.findList(query);
				for (PubgUserMatch pubgUserMatch : userMatchList) {
					
					// 已经通过的
					if ((UserMatchConstant.USER_MATCH_20.getId() + "").equals(pubgUserMatch.getUserState())) {
						
						// 更新 队员的参赛总数
						sb = new StringBuffer();
						sb.append(" UPDATE ");
						sb.append("   pubg_user ");
						sb.append(" SET ");
						sb.append("   MATCH_AMOUNT = MATCH_AMOUNT - 1 ");
						sb.append(" WHERE ");
						sb.append("   ROW_ID = ? AND USER_ROLE = ? ");
						this.baseDao.safeUpdate(sb.toString(), 1, UserMatchConstant.USER_MATCH_20.getId(), 
								pubgUserMatch.getUserId(), UserConstant.USER_ROLE_10);
						
						// 更新用户-战队的参赛数
						sb = new StringBuffer();
						sb.append(" UPDATE ");
						sb.append("   pubg_user_team ");
						sb.append(" SET ");
						sb.append("   MATCH_AMOUNT = MATCH_AMOUNT - 1 ");
						sb.append(" WHERE ");
						sb.append("   USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? ");
						this.baseDao.safeUpdate(sb.toString(), 1, UserMatchConstant.USER_MATCH_20.getId(), 
								pubgUserMatch.getUserId(), pubgUserMatch.getTeamId(), pubgUserMatch.getClubId());
						
						// 更新用户-俱乐部的参赛数
						sb = new StringBuffer();
						sb.append(" UPDATE ");
						sb.append("   pubg_user_club ");
						sb.append(" SET ");
						sb.append("   MATCH_AMOUNT = MATCH_AMOUNT - 1 ");
						sb.append(" WHERE ");
						sb.append("   USER_ID = ? AND CLUB_ID = ? ");
						this.baseDao.safeUpdate(sb.toString(), 1, UserMatchConstant.USER_MATCH_20.getId(), 
								pubgUserMatch.getUserId(), pubgUserMatch.getClubId());
					}
					
					// 更新队员-赛事
					sb = new StringBuffer();
					sb.append(" UPDATE ");
					sb.append("   pubg_user_match ");
					sb.append(" SET ");
					sb.append("   USER_STATE = ? ");
					sb.append(" WHERE ");
					sb.append("   USER_ID = ? AND TEAM_ID = ? AND MATCH_ID = ? ");
					sb.append("    AND USER_STATE IN (10,20)");
					this.baseDao.safeUpdate(sb.toString(), 1, UserMatchConstant.USER_MATCH_50.getId(), 
							pubgUserMatch.getUserId(), pubgUserMatch.getTeamId(), 
							pubgUserMatch.getMatchId(), UserMatchConstant.USER_MATCH_10.getId());
					
					// 更新队员所在战队的余额
					query = new Query();
					query.put("USER_ID", pubgUserMatch.getUserId());
					query.put("TEAM_ID", pubgUserMatch.getTeamId());
					pubgUserTeam = pubgUserTeamService.find(query);
					sb = new StringBuffer();
					sb.append(" UPDATE ");
					sb.append("   pubg_user_team ");
					sb.append(" SET ");
					sb.append("   USER_TEAM_BALANCE = USER_TEAM_BALANCE + ? ");
					sb.append(" WHERE ");
					sb.append("   USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? AND USER_TEAM_BALANCE = ? ");
					this.baseDao.safeUpdate(sb.toString(), 1, pubgUserMatch.getApplyFee(), 
							pubgUserMatch.getUserId(), pubgUserMatch.getTeamId(), 
							pubgUserMatch.getClubId(), pubgUserTeam.getUserTeamBalance());
					
					// 更新队员的总余额
					sb = new StringBuffer(255);
					sb.append(" UPDATE ");
					sb.append("   pubg_user ");
					sb.append(" SET ");
					sb.append("   BALANCE = BALANCE + ? ");
					sb.append(" WHERE ");
					sb.append("   ROW_ID = ? AND USER_ROLE = ? ");
					this.baseDao.safeUpdate(sb.toString(), 1, pubgUserMatch.getApplyFee(), 
							pubgUserMatch.getUserId(), UserConstant.USER_ROLE_10.getId());
					
					// 生成流水
					PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
					pubgFinanceFlowDetail.setClubId(pubgUserMatch.getClubId());
					pubgFinanceFlowDetail.setClubName(pubgUserMatch.getClubName());
					pubgFinanceFlowDetail.setTeamId(pubgUserMatch.getTeamId());
					pubgFinanceFlowDetail.setTeamName(pubgUserMatch.getTeamName());
					pubgFinanceFlowDetail.setUserId(pubgUserMatch.getUserId());
					pubgFinanceFlowDetail.setUserAccount(pubgUserMatch.getUserAccount());
					pubgFinanceFlowDetail.setInOutFlag(1);
					pubgFinanceFlowDetail.setTradeMoney(pubgUserMatch.getApplyFee());
					pubgFinanceFlowDetail.setTradeMoneyAfter(pubgUserTeam.getUserTeamBalance() + pubgUserMatch.getApplyFee());
					pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_CANCEL_REDUCE.key());
					pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_CANCEL_REDUCE.value());
					pubgFinanceFlowDetail.setRelationOrderNo(pubgUserMatch.getMatchId() + "_" + pubgUserMatch.getMatchName());
					pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
					this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("更新赛事状态出错！", e);
		}
    }
    
    /**
     * 计算队员、战队、俱乐部所得金额
     * 
     * @author 朱建文 创建时间：2018年4月8日 下午7:54:06
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
    public void computeMatchBonus(PubgMatch pubgMatch) throws Exception {
    	StringBuffer sb = new StringBuffer();
    	try {
    		
    		// 删除赛事奖励
    		sb.append(" DELETE FROM pubg_match_settlement WHERE MATCH_ID = ? AND USER_ID IS NULL ");
    		this.baseDao.safeUpdate(sb.toString(), 0, pubgMatch.getRowId());
    		
			// 查询队员名次及获取比例（按名次分组）
    		sb = new StringBuffer();
			sb.append(" SELECT ");
			sb.append("   b.USER_ID userId, b.USER_ACCOUNT userAccount, b.TEAM_ID teamId, b.TEAM_NAME teamName, b.OBTAIN_RANK obtainBank, ");
			sb.append("   b.CLUB_ID clubId, b.CLUB_NAME clubName, a.AWARD_VALUE awardValue, b.INVITE_FROM inviteFrom ");
			sb.append(" FROM ");
			sb.append("   pubg_match_reward a LEFT JOIN pubg_match_settlement b ");
			sb.append("   ON a.MATCH_ID = b.MATCH_ID AND a.RANKING = b.OBTAIN_RANK ");
			sb.append(" WHERE ");
			sb.append("   b.MATCH_ID = ? ");
			List<Map<String, Object>> dataList = this.baseDao.findMapList(sb.toString(), pubgMatch.getRowId());
			
			// 查询每个名次的获奖人数SQL
			String selectEveryRank = "SELECT MATCH_ID, CLUB_ID, CLUB_NAME, TEAM_ID, TEAM_NAME, ";
			selectEveryRank += " USER_ID, USER_ACCOUNT, USER_ACCOUNT, OBTAIN_RANK ";
			selectEveryRank += " FROM pubg_match_settlement WHERE MATCH_ID = ? AND OBTAIN_RANK = ? ";
			List<PubgMatchSettlement> matchSettlementList = null; // 查询结果
			PubgMatchSettlement matchSettlementTemp = null; // 临时使用 需要从该对象中获取 提交时间、提交人、确认时间、确认人等信息
			
			double awardValue = 0.0; // 奖励比值
			double obtainAward = 0.0; // 队员获取的奖励
			double memberAwardSum = 0.0; // 队员奖励总计
			for (Map<String, Object> map : dataList) {
				awardValue = ObjectUtil.convert(map.get("awardValue") + "", 0.0);
				
				// 计算每个名次的获奖金额
				obtainAward = pubgMatch.getApplySumTemp() * awardValue;
				
				// 查询每个名次的获奖人数
				matchSettlementList = this.baseDao.findList(selectEveryRank, 
						RowMapperFactory.newInstance(PubgMatchSettlement.class), pubgMatch.getRowId(), map.get("obtainBank"));
				for (PubgMatchSettlement winMember : matchSettlementList) {
					matchSettlementTemp = winMember;
					
					// 目前是每个获奖者 平分 名次奖金   （保留2位小数，其余的直接抹掉，高老师定的）
					obtainAward = obtainAward / matchSettlementList.size();
					if ((obtainAward + "").indexOf(".") > 0) {
						obtainAward = ObjectUtil.convertDouble((obtainAward + "").substring((obtainAward + "").indexOf(".") + 2));
					}
					
					// 更新 赛事资金表 奖励所得
					sb = new StringBuffer();
					sb.append(" UPDATE ");
					sb.append("   pubg_match_settlement ");
					sb.append(" SET ");
					sb.append("   OBTAIN_AWARD = ? ");
					sb.append(" WHERE ");
					sb.append("   MATCH_ID = ? AND TEAM_ID = ? AND USER_ID = ? AND OBTAIN_RANK = ?");
					this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, pubgMatch.getRowId(), winMember.getTeamId(),
							winMember.getUserId(), winMember.getObtainRank());
				}
				
				// 计算所有队员的奖励总和
				memberAwardSum += obtainAward;
			}
			
			// 计算总利润		利润 = 总费用 - 用户奖励
			double profitSum = pubgMatch.getApplySumFinal() - memberAwardSum;
			
			// 查询每个战队的贡献人数
			sb = new StringBuffer();
			sb.append(" SELECT ");
			sb.append("   MATCH_ID matchId, CLUB_ID clubId, CLUB_NAME clubName, TEAM_ID teamId, TEAM_NAME teamName, COUNT(0) memberNum, ");
			sb.append("   RESULT_SUBMIT_ID, RESULT_SUBMIT_ACCOUNT, RESULT_SUBMIT_TIME, ");
			sb.append("   RESULT_CONFIRM_ID, RESULT_CONFIRM_ACCOUNT, RESULT_CONFIRM_TIME ");
			sb.append(" FROM ");
			sb.append("   pubg_user_match ");
			sb.append(" WHERE ");
			sb.append("   MATCH_ID = ? AND CLUB_ID = ? ");
			sb.append(" GROUP BY ");
			sb.append("   INVITE_FROM ");
			dataList = this.baseDao.findMapList(sb.toString(), pubgMatch.getRowId(), pubgMatch.getClubId());
			
			// 查询战队的余额
			String selectBalance = "SELECT TEAM_BALANCE FROM pubg_team WHERE ROW_ID = ?";
			double tempBalance = 0.0;
			
			// 计算战队所得	战队提成 = 战队贡献比 * 提成比例 * 总利润
			int memberNum = 0;
			double teamProfit = 0.0;
			double teamProfitSum = 0.0; // 战队提成之和
			PubgMatchSettlement pubgMatchSettlement = null;
			for (Map<String, Object> map : dataList) {
				memberNum = ObjectUtil.convert(map.get("memberNum"), 0);
				teamProfit = (memberNum / pubgMatch.getMatchPeopleNum()) * pubgMatch.getAwardWay() * profitSum;
				teamProfitSum += teamProfit;
				
				// 查询战队当前余额
				tempBalance = this.baseDao.find(selectBalance, Double.class, map.get("teamId"));
				
				// 更新战队的余额
				this.baseDao.safeUpdate(sb.toString(), 1, teamProfit, map.get("teamId"), tempBalance);
				
				// 插入分成记录
				pubgMatchSettlement = new PubgMatchSettlement();
				pubgMatchSettlement.setMatchId(pubgMatch.getRowId());
				pubgMatchSettlement.setMatchName(pubgMatch.getMatchName());
				pubgMatchSettlement.setMatchType(pubgMatch.getMatchTypeId());
				pubgMatchSettlement.setMatchTypeName(pubgMatch.getMatchTeamName());
				pubgMatchSettlement.setClubId(ObjectUtil.convertLong(map.get("clubId")));
				pubgMatchSettlement.setClubName(ObjectUtil.convert(map.get("clubName")));
				pubgMatchSettlement.setTeamId(ObjectUtil.convertLong(map.get("teamId")));
				pubgMatchSettlement.setTeamName(ObjectUtil.convert(map.get("teamName")));
				pubgMatchSettlement.setResultSubmitId(ObjectUtil.convertLong(map.get("RESULT_SUBMIT_ID")));
				pubgMatchSettlement.setResultSubmitAccount(map.get("RESULT_SUBMIT_ACCOUNT") + "");
				pubgMatchSettlement.setResultSubmitTime(map.get("RESULT_SUBMIT_TIME") + "");
				pubgMatchSettlement.setResultConfirmId(ObjectUtil.convertLong(map.get("RESULT_CONFIRM_ID")));
				pubgMatchSettlement.setResultConfirmAccount(map.get("RESULT_CONFIRM_ACCOUNT") + "");
				pubgMatchSettlement.setResultConfirmTime(map.get("RESULT_CONFIRM_TIME") + "");
				pubgMatchSettlement.setObtainAward(teamProfit);
				this.pubgMatchSettlementService.saveObj(pubgMatchSettlement);
				
			}
			
			// 计算俱乐部所得     俱乐部收入 = 利润 - 战队提成之和
			double clubProfit = profitSum - teamProfitSum;
			
			// 插入分成记录
			pubgMatchSettlement = new PubgMatchSettlement();
			pubgMatchSettlement.setMatchId(pubgMatch.getRowId());
			pubgMatchSettlement.setMatchName(pubgMatch.getMatchName());
			pubgMatchSettlement.setMatchType(pubgMatch.getMatchTypeId());
			pubgMatchSettlement.setMatchTypeName(pubgMatch.getMatchTeamName());
			pubgMatchSettlement.setClubId(pubgMatch.getClubId());
			pubgMatchSettlement.setClubName(pubgMatch.getClubName());
			pubgMatchSettlement.setResultSubmitId(matchSettlementTemp.getResultSubmitId());
			pubgMatchSettlement.setResultSubmitAccount(matchSettlementTemp.getResultSubmitAccount());
			pubgMatchSettlement.setResultSubmitTime(matchSettlementTemp.getResultSubmitTime());
			pubgMatchSettlement.setResultConfirmId(matchSettlementTemp.getResultConfirmId());
			pubgMatchSettlement.setResultConfirmAccount(matchSettlementTemp.getResultConfirmAccount());
			pubgMatchSettlement.setResultConfirmTime(matchSettlementTemp.getResultConfirmTime());
			pubgMatchSettlement.setObtainAward(clubProfit);
			this.pubgMatchSettlementService.saveObj(pubgMatchSettlement);
			
		} catch (Exception e) {
			throw new RuntimeException("计算队员、战队、俱乐部所得金额出错！", e);
		}
    }
    
    /**
     * 确认比赛结果
     * 
     * @author 朱建文 创建时间：2018年4月8日 下午7:54:06
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
    public void confirmMatchResult(PubgMatch pubgMatch, PubgClub pubgClub, PubgUser pubgUser) throws Exception {
    	StringBuffer sb = new StringBuffer();
    	Map<String, Object> dataMap = null;
    	try {
    		
    		// 更新确认人信息
    		sb.append(" UPDATE ");
    		sb.append("   pubg_match_settlement ");
    		sb.append(" SET ");
    		sb.append("   RESULT_CONFIRM_ID = ?, RESULT_CONFIRM_ACCOUNT = ?, RESULT_CONFIRM_TIME = ? ");
    		sb.append(" WHERE ");
    		sb.append("   MATCH_ID = ? AND CLUB_ID = ? ");
    		this.baseDao.safeUpdate(sb.toString(), 0, 
    				pubgUser.getRowId(), pubgUser.getUserAccount(), DateUtil.getCurrentDateTime(),
    				pubgMatch.getRowId(), pubgMatch.getClubId());
    		
    		// 查询 战绩信息 数据
    		dataMap = this.pubgMatchSettlementService.getMatchSettlementAuditList(pubgMatch.getRowId(), pubgClub.getRowId());
    		if (dataMap == null || dataMap.isEmpty()) {
				throw new RuntimeException("未查询到 战绩信息");
			}
    		
    		List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataMap.get("data");

    		// 查询队员-战队关系
    		Query query = new Query();
    		PubgUserTeam pubgUserTeam = null;
    		
    		double obtainAward = 0.0; // 队员获取的奖励
    		PubgFinanceFlowDetail pubgFinanceFlowDetail = null;
    		for (Map<String, Object> map : dataList) {
    			obtainAward = ObjectUtil.convert(map.get("obtainAward"), 0.0);
    			
				// 更新队员-赛事 所得
				sb = new StringBuffer();
				sb.append(" UPDATE ");
				sb.append("   pubg_user_match ");
				sb.append(" SET ");
				sb.append("   RESULT_AUDIT_TIME = ?, OBTAIN_AWARD = ? ");
				sb.append(" WHERE ");
				sb.append("   MATCH_ID = ? AND USER_ID = ? AND USER_STATE = '20'");
				this.baseDao.safeUpdate(sb.toString(), 1, DateUtil.getCurrentDateTime(), obtainAward,
						pubgMatch.getRowId(), ObjectUtil.convertLong(map.get("rowId")));

				// 查询队员所在战队的余额
				query.put("USER_ID", map.get("rowId"));
				query.put("TEAM_ID", map.get("teamId"));
				query.put("CLUB_ID", pubgClub.getRowId());
				query.put("RELATION_STATE", 2);
				pubgUserTeam = this.pubgUserTeamService.find(query);
				if (pubgUserTeam == null) {
					continue;
				}
				
				// 更新队员-战队 获奖总场次、获奖总金额
				sb = new StringBuffer();
				sb.append(" UPDATE ");
				sb.append("   pubg_user_team ");
				sb.append(" SET ");
				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ? ");
				sb.append(" WHERE ");
				sb.append("   TEAM_ID = ? AND USER_ID = ? AND WIN_SUM = ? AND RELATION_STATE = 2 ");
				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward,
						map.get("teamId"), map.get("rowId"), pubgUserTeam.getWinSum());
				
				// 更新队员-俱乐部  获奖总场次、获奖总金额
				sb = new StringBuffer();
				sb.append(" UPDATE ");
				sb.append("   pubg_user_club ");
				sb.append(" SET ");
				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ? ");
				sb.append(" WHERE ");
				sb.append("   CLUB_ID = ? AND USER_ID = ? AND RELATION_STATE = 2 ");
				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, pubgClub.getRowId(), map.get("rowId"));
				
				// 更新队员所得（获奖总数、奖励合计）
				sb = new StringBuffer();
				sb.append(" UPDATE ");
				sb.append("   pubg_user ");
				sb.append(" SET ");
				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ?, BALANCE = BALANCE + ? ");
				sb.append(" WHERE ");
				sb.append("   ROW_ID = ? AND USER_ROLE = 10");
				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, obtainAward, map.get("rowId"));
				
				// 记录资金流水
				pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
				pubgFinanceFlowDetail.setClubId(pubgClub.getRowId());
				pubgFinanceFlowDetail.setClubName(pubgClub.getClubName());
				pubgFinanceFlowDetail.setTeamId(pubgUserTeam.getTeamId());
				pubgFinanceFlowDetail.setTeamName(pubgUserTeam.getTeamName());
				pubgFinanceFlowDetail.setUserId(ObjectUtil.convertLong(map.get("rowId")));
				pubgFinanceFlowDetail.setUserAccount(pubgUserTeam.getUserAccount());
				pubgFinanceFlowDetail.setInOutFlag(1);
				pubgFinanceFlowDetail.setTradeMoney(obtainAward);
				pubgFinanceFlowDetail.setTradeMoneyAfter(pubgUserTeam.getUserTeamBalance() + obtainAward);
				pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
				pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
				pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
				pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
				this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
			}
    		
    		// 计算总利润		利润 = 总费用 - 用户奖励
    		double memberAwardSum = ObjectUtil.convert(dataMap.get("userAward"), 0.0); // 用户奖励总和
    		double profitSum = pubgMatch.getApplySumFinal() - memberAwardSum;
    		
    		// 查询每个战队的贡献人数
    		sb = new StringBuffer();
    		sb.append(" SELECT ");
    		sb.append("   MATCH_ID matchId, CLUB_ID clubId, CLUB_NAME clubName, TEAM_ID teamId, TEAM_NAME teamName, OBTAIN_AWARD obtainAward ");
    		sb.append("   ");
    		sb.append(" FROM ");
    		sb.append("   pubg_match_settlement ");
    		sb.append(" WHERE ");
    		sb.append("   MATCH_ID = ? AND CLUB_ID = ? AND USER_ID IS NULL AND TEAM_ID IS NOT NULL ");
    		dataList = this.baseDao.findMapList(sb.toString(), pubgMatch.getRowId(), pubgMatch.getClubId());
    		
    		// 查询战队的余额
    		String selectBalance = "SELECT TEAM_BALANCE FROM pubg_team WHERE ROW_ID = ?";
    		double tempBalance = 0.0;
    		
    		// 更新战队余额SQL
    		sb = new StringBuffer();
    		sb.append(" UPDATE ");
    		sb.append("   pubg_team ");
    		sb.append(" SET ");
    		sb.append("   TEAM_BALANCE = TEAM_BALANCE + ? ");
    		sb.append(" WHERE ");
    		sb.append("   ROW_ID = ? AND TEAM_BALANCE = ? ");
    		
    		// 计算战队所得	战队提成 = 战队贡献比 * 提成比例 * 总利润
    		double teamProfit = 0.0;
    		for (Map<String, Object> map : dataList) {
    			teamProfit = ObjectUtil.convert(map.get("obtainAward"), 0.0);
    			
    			if (StringUtil.isEmpty(map.get("teamId"))) {
					continue;
				}
    			
    			// 查询战队当前余额
    			tempBalance = this.baseDao.find(selectBalance, Double.class, map.get("teamId"));
    			
    			// 更新战队的余额
    			this.baseDao.safeUpdate(sb.toString(), 1, teamProfit, map.get("teamId"), tempBalance);
    			
    			// 记录资金流水
    			pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    			pubgFinanceFlowDetail.setClubId(pubgMatch.getClubId());
    			pubgFinanceFlowDetail.setClubName(pubgMatch.getClubName());
    			pubgFinanceFlowDetail.setTeamId(ObjectUtil.convertLong(map.get("teamId")));
    			pubgFinanceFlowDetail.setTeamName(map.get("teamId") + "");
    			pubgFinanceFlowDetail.setInOutFlag(1);
    			pubgFinanceFlowDetail.setTradeMoney(teamProfit);
    			pubgFinanceFlowDetail.setTradeMoneyAfter(tempBalance + teamProfit);
    			pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
    			pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
    			pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
    			pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    			this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    			
    		}
    		
    		// 计算俱乐部所得     俱乐部收入 = 利润 - 战队提成之和
    		double teamProfitSum = ObjectUtil.convert(dataMap.get("teamAward"), 0.0);; // 战队提成之和
    		double clubProfit = profitSum - teamProfitSum;
    		
    		// 更新俱乐部余额
    		sb = new StringBuffer();
    		sb.append(" UPDATE ");
    		sb.append("   pubg_club ");
    		sb.append(" SET ");
    		sb.append("   CLUB_BALANCE = CLUB_BALANCE + ? ");
    		sb.append(" WHERE ");
    		sb.append("   ROW_ID = ? AND CLUB_BALANCE = ? ");
    		this.baseDao.safeUpdate(sb.toString(), 1, clubProfit, pubgClub.getRowId(), pubgClub.getClubBalance());
    		
    		// 记录资金流水
    		pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    		pubgFinanceFlowDetail.setClubId(pubgMatch.getClubId());
    		pubgFinanceFlowDetail.setClubName(pubgMatch.getClubName());
    		pubgFinanceFlowDetail.setInOutFlag(1);
    		pubgFinanceFlowDetail.setTradeMoney(clubProfit);
    		pubgFinanceFlowDetail.setTradeMoneyAfter(pubgClub.getClubBalance() + clubProfit);
    		pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
    		pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
    		pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
    		pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    		this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    		
    		// 更新赛事状态
    		sb = new StringBuffer();
    		sb.append(" UPDATE ");
    		sb.append("   pubg_match ");
    		sb.append(" SET ");
    		sb.append("   MATCH_STATE = ? ");
    		sb.append(" WHERE ");
    		sb.append("   ROW_ID = ? AND CLUB_ID = ? AND MATCH_STATE = ? ");
    		this.baseDao.safeUpdate(sb.toString(), 1, MatchConstant.MATCH_STATE_70.getId(), 
    				pubgMatch.getRowId(), pubgMatch.getClubId(), MatchConstant.MATCH_STATE_60.getId());
    	} catch (Exception e) {
    		throw new RuntimeException("确认比赛结果出错！", e);
    	}
    }
    
    /**
     * 确认比赛结果
     * 
     * @author 朱建文 创建时间：2018年4月8日 下午7:54:06
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}) //任何异常 都需要回滚
    public void confirmMatchResultBACK(PubgMatch pubgMatch, PubgClub pubgClub, PubgUser pubgUser) throws Exception {
    	StringBuffer sb = new StringBuffer();
    	try {
    		
    		// 更新确认人信息
    		sb.append(" UPDATE ");
    		sb.append("   pubg_match_settlement ");
    		sb.append(" SET ");
    		sb.append("   RESULT_CONFIRM_ID = ?, RESULT_CONFIRM_ACCOUNT = ?, RESULT_CONFIRM_TIME = ? ");
    		sb.append(" WHERE ");
    		sb.append("   MATCH_ID = ? AND CLUB_ID = ? ");
    		this.baseDao.safeUpdate(sb.toString(), 0, 
    				pubgUser.getRowId(), pubgUser.getUserAccount(), DateUtil.getCurrentDateTime(),
    				pubgMatch.getRowId(), pubgMatch.getClubId());
    		
    		
    		// 查询队员名次及获取比例（按名次分组）
    		sb = new StringBuffer();
    		sb.append(" SELECT ");
    		sb.append("   b.USER_ID userId, b.USER_ACCOUNT userAccount, b.TEAM_ID teamId, b.TEAM_NAME teamName, b.OBTAIN_RANK obtainBank, ");
    		sb.append("   b.CLUB_ID clubId, b.CLUB_NAME clubName, a.AWARD_VALUE awardValue, b.INVITE_FROM inviteFrom ");
    		sb.append(" FROM ");
    		sb.append("   pubg_match_reward a LEFT JOIN pubg_match_settlement b ");
    		sb.append("   ON a.MATCH_ID = b.MATCH_ID AND a.RANKING = b.OBTAIN_RANK ");
    		sb.append(" WHERE ");
    		sb.append("   b.MATCH_ID = ? ");
    		List<Map<String, Object>> dataList = this.baseDao.findMapList(sb.toString(), pubgMatch.getRowId());
    		
    		// 查询每个名次的获奖人数SQL
    		String selectEveryRank = "SELECT MATCH_ID, CLUB_ID, CLUB_NAME, TEAM_ID, TEAM_NAME, ";
    		selectEveryRank += " USER_ID, USER_ACCOUNT, USER_ACCOUNT, OBTAIN_RANK ";
    		selectEveryRank += " FROM pubg_match_settlement WHERE MATCH_ID = ? AND OBTAIN_RANK = ? ";
    		List<PubgMatchSettlement> matchSettlementList = null; // 查询结果
    		PubgMatchSettlement matchSettlementTemp = null; // 临时使用 需要从该对象中获取 提交时间、提交人、确认时间、确认人等信息
    		
    		// 查询队员-战队关系
    		Query query = new Query();
    		
    		double awardValue = 0.0; // 奖励比值
    		double obtainAward = 0.0; // 队员获取的奖励
    		double memberAwardSum = 0.0; // 队员奖励总计
    		PubgFinanceFlowDetail pubgFinanceFlowDetail = null;
    		PubgUserTeam pubgUserTeam = null;
    		for (Map<String, Object> map : dataList) {
    			awardValue = ObjectUtil.convert(map.get("awardValue") + "", 0.0);
    			
    			// 计算每个名次的获奖金额
    			obtainAward = pubgMatch.getApplySumTemp() * awardValue;
    			
    			// 查询每个名次的获奖人数
    			matchSettlementList = this.baseDao.findList(selectEveryRank, 
    					RowMapperFactory.newInstance(PubgMatchSettlement.class), pubgMatch.getRowId(), map.get("obtainBank"));
    			for (PubgMatchSettlement winMember : matchSettlementList) {
    				matchSettlementTemp = winMember;
    				
    				// 目前是每个获奖者 平分 名次奖金   （保留2位小数，其余的直接抹掉，高老师定的）
    				obtainAward = obtainAward / matchSettlementList.size();
    				if ((obtainAward + "").indexOf(".") > 0) {
    					obtainAward = ObjectUtil.convertDouble((obtainAward + "").substring((obtainAward + "").indexOf(".") + 2));
    				}
    				
    				// 查询队员所在战队的余额
    				query.put("USER_ID", winMember.getUserId());
    				query.put("TEAM_ID", winMember.getTeamId());
    				query.put("CLUB_ID", winMember.getClubId());
    				pubgUserTeam = this.pubgUserTeamService.find(query);
    				
    				// 更新队员-赛事 所得
    				sb = new StringBuffer();
    				sb.append(" UPDATE ");
    				sb.append("   pubg_user_match ");
    				sb.append(" SET ");
    				sb.append("   RESULT_AUDIT_TIME = ?, OBTAIN_AWARD = ? ");
    				sb.append(" WHERE ");
    				sb.append("   MATCH_ID = ? AND USER_ID = ? ");
    				this.baseDao.safeUpdate(sb.toString(), 1, DateUtil.getCurrentDateTime(), obtainAward,
    						pubgMatch.getRowId(), winMember.getUserId());
    				
    				// 更新队员-战队 获奖总场次、获奖总金额
    				sb = new StringBuffer();
    				sb.append(" UPDATE ");
    				sb.append("   pubg_user_team ");
    				sb.append(" SET ");
    				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ? ");
    				sb.append(" WHERE ");
    				sb.append("   TEAM_ID = ? AND USER_ID = ? AND WIN_SUM = ? ");
    				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward,
    						winMember.getTeamId(), winMember.getUserId(), pubgUserTeam.getWinSum());
    				
    				// 更新队员-俱乐部  获奖总场次、获奖总金额
    				sb = new StringBuffer();
    				sb.append(" UPDATE ");
    				sb.append("   pubg_user_club ");
    				sb.append(" SET ");
    				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ? ");
    				sb.append(" WHERE ");
    				sb.append("   CLUB_ID = ? AND USER_ID = ? ");
    				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, winMember.getClubId(), winMember.getUserId());
    				
    				// 更新队员所得（获奖总数、奖励合计）
    				sb = new StringBuffer();
    				sb.append(" UPDATE ");
    				sb.append("   pubg_user ");
    				sb.append(" SET ");
    				sb.append("   WIN_AMOUNT = WIN_AMOUNT + 1, WIN_SUM = WIN_SUM + ? ");
    				sb.append(" WHERE ");
    				sb.append("   ROW_ID = ? ");
    				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, winMember.getUserId());
    				
    				// 更新 赛事资金表 奖励所得
    				sb = new StringBuffer();
    				sb.append(" UPDATE ");
    				sb.append("   pubg_match_settlement ");
    				sb.append(" SET ");
    				sb.append("   OBTAIN_AWARD = ? ");
    				sb.append(" WHERE ");
    				sb.append("   MATCH_ID = ? AND TEAM_ID = ? AND USER_ID = ? AND OBTAIN_RANK = ?");
    				this.baseDao.safeUpdate(sb.toString(), 1, obtainAward, pubgMatch.getRowId(), winMember.getTeamId(),
    						winMember.getUserId(), winMember.getObtainRank());
    				
    				// 记录资金流水
    				pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    				pubgFinanceFlowDetail.setClubId(winMember.getClubId());
    				pubgFinanceFlowDetail.setClubName(winMember.getClubName());
    				pubgFinanceFlowDetail.setTeamId(winMember.getTeamId());
    				pubgFinanceFlowDetail.setTeamName(winMember.getTeamName());
    				pubgFinanceFlowDetail.setUserId(winMember.getUserId());
    				pubgFinanceFlowDetail.setUserAccount(winMember.getUserAccount());
    				pubgFinanceFlowDetail.setInOutFlag(1);
    				pubgFinanceFlowDetail.setTradeMoney(obtainAward);
    				pubgFinanceFlowDetail.setTradeMoneyAfter(pubgUserTeam.getUserTeamBalance() + obtainAward);
    				pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
    				pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
    				pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
    				pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    				this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    			}
    			
    			// 计算所有队员的奖励总和
    			memberAwardSum += obtainAward;
    		}
    		
    		// 计算总利润		利润 = 总费用 - 用户奖励
    		double profitSum = pubgMatch.getApplySumFinal() - memberAwardSum;
    		
    		// 查询每个战队的贡献人数
    		sb = new StringBuffer();
    		sb.append(" SELECT ");
    		sb.append("   MATCH_ID matchId, CLUB_ID clubId, CLUB_NAME clubName, TEAM_ID teamId, TEAM_NAME teamName, COUNT(0) memberNum, ");
    		sb.append("   RESULT_SUBMIT_ID, RESULT_SUBMIT_ACCOUNT, RESULT_SUBMIT_TIME, ");
    		sb.append("   RESULT_CONFIRM_ID, RESULT_CONFIRM_ACCOUNT, RESULT_CONFIRM_TIME ");
    		sb.append(" FROM ");
    		sb.append("   pubg_user_match ");
    		sb.append(" WHERE ");
    		sb.append("   MATCH_ID = ? AND CLUB_ID = ? ");
    		sb.append(" GROUP BY ");
    		sb.append("   INVITE_FROM ");
    		dataList = this.baseDao.findMapList(sb.toString(), pubgMatch.getRowId(), pubgMatch.getClubId());
    		
    		// 查询战队的余额
    		String selectBalance = "SELECT TEAM_BALANCE FROM pubg_team WHERE ROW_ID = ?";
    		double tempBalance = 0.0;
    		
    		// 更新战队余额SQL
    		sb = new StringBuffer();
    		sb.append(" UPDATE ");
    		sb.append("   pubg_team ");
    		sb.append(" SET ");
    		sb.append("   TEAM_BALANCE = TEAM_BALANCE + ? ");
    		sb.append(" WHERE ");
    		sb.append("   ROW_ID = ? AND TEAM_BALANCE = ? ");
    		
    		// 计算战队所得	战队提成 = 战队贡献比 * 提成比例 * 总利润
    		int memberNum = 0;
    		double teamProfit = 0.0;
    		double teamProfitSum = 0.0; // 战队提成之和
    		PubgMatchSettlement pubgMatchSettlement = null;
    		for (Map<String, Object> map : dataList) {
    			memberNum = ObjectUtil.convert(map.get("memberNum"), 0);
    			teamProfit = (memberNum / pubgMatch.getMatchPeopleNum()) * pubgMatch.getAwardWay() * profitSum;
    			teamProfitSum += teamProfit;
    			
    			// 查询战队当前余额
    			tempBalance = this.baseDao.find(selectBalance, Double.class, map.get("teamId"));
    			
    			// 更新战队的余额
    			this.baseDao.safeUpdate(sb.toString(), 1, teamProfit, map.get("teamId"), tempBalance);
    			
    			// 插入分成记录
    			pubgMatchSettlement = new PubgMatchSettlement();
    			pubgMatchSettlement.setMatchId(pubgMatch.getRowId());
    			pubgMatchSettlement.setMatchName(pubgMatch.getMatchName());
    			pubgMatchSettlement.setMatchType(pubgMatch.getMatchTypeId());
    			pubgMatchSettlement.setMatchTypeName(pubgMatch.getMatchTeamName());
    			pubgMatchSettlement.setClubId(ObjectUtil.convertLong(map.get("clubId")));
    			pubgMatchSettlement.setClubName(ObjectUtil.convert(map.get("clubName")));
    			pubgMatchSettlement.setTeamId(ObjectUtil.convertLong(map.get("teamId")));
    			pubgMatchSettlement.setTeamName(ObjectUtil.convert(map.get("teamName")));
    			pubgMatchSettlement.setResultSubmitId(ObjectUtil.convertLong(map.get("RESULT_SUBMIT_ID")));
    			pubgMatchSettlement.setResultSubmitAccount(map.get("RESULT_SUBMIT_ACCOUNT") + "");
    			pubgMatchSettlement.setResultSubmitTime(map.get("RESULT_SUBMIT_TIME") + "");
    			pubgMatchSettlement.setResultConfirmId(ObjectUtil.convertLong(map.get("RESULT_CONFIRM_ID")));
    			pubgMatchSettlement.setResultConfirmAccount(map.get("RESULT_CONFIRM_ACCOUNT") + "");
    			pubgMatchSettlement.setResultConfirmTime(map.get("RESULT_CONFIRM_TIME") + "");
    			pubgMatchSettlement.setObtainAward(teamProfit);;
    			this.pubgMatchSettlementService.saveObj(pubgMatchSettlement);
    			
    			// 记录资金流水
    			pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    			pubgFinanceFlowDetail.setClubId(pubgMatch.getClubId());
    			pubgFinanceFlowDetail.setClubName(pubgMatch.getClubName());
    			pubgFinanceFlowDetail.setTeamId(pubgMatchSettlement.getTeamId());
    			pubgFinanceFlowDetail.setTeamName(pubgMatchSettlement.getTeamName());
    			pubgFinanceFlowDetail.setInOutFlag(1);
    			pubgFinanceFlowDetail.setTradeMoney(teamProfit);
    			pubgFinanceFlowDetail.setTradeMoneyAfter(tempBalance + teamProfit);
    			pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
    			pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
    			pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
    			pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    			this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    		}
    		
    		// 计算俱乐部所得     俱乐部收入 = 利润 - 战队提成之和
    		double clubProfit = profitSum - teamProfitSum;
    		
    		// 更新俱乐部余额
    		sb = new StringBuffer();
    		sb.append(" UPDATE ");
    		sb.append("   pubg_club ");
    		sb.append(" SET ");
    		sb.append("   CLUB_BALANCE = CLUB_BALANCE + ? ");
    		sb.append(" WHERE ");
    		sb.append("   ROW_ID = ? AND CLUB_BALANCE = ? ");
    		this.baseDao.safeUpdate(sb.toString(), 1, clubProfit, pubgClub.getRowId(), pubgClub.getClubBalance());
    		
    		// 插入分成记录
    		pubgMatchSettlement = new PubgMatchSettlement();
    		pubgMatchSettlement.setMatchId(pubgMatch.getRowId());
    		pubgMatchSettlement.setMatchName(pubgMatch.getMatchName());
    		pubgMatchSettlement.setMatchType(pubgMatch.getMatchTypeId());
    		pubgMatchSettlement.setMatchTypeName(pubgMatch.getMatchTeamName());
    		pubgMatchSettlement.setClubId(pubgMatch.getClubId());
    		pubgMatchSettlement.setClubName(pubgMatch.getClubName());
    		pubgMatchSettlement.setResultSubmitId(matchSettlementTemp.getResultSubmitId());
    		pubgMatchSettlement.setResultSubmitAccount(matchSettlementTemp.getResultSubmitAccount());
    		pubgMatchSettlement.setResultSubmitTime(matchSettlementTemp.getResultSubmitTime());
    		pubgMatchSettlement.setResultConfirmId(matchSettlementTemp.getResultConfirmId());
    		pubgMatchSettlement.setResultConfirmAccount(matchSettlementTemp.getResultConfirmAccount());
    		pubgMatchSettlement.setResultConfirmTime(matchSettlementTemp.getResultConfirmTime());
    		pubgMatchSettlement.setObtainAward(teamProfit);
    		this.pubgMatchSettlementService.saveObj(pubgMatchSettlement);
    		
    		// 记录资金流水
    		pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
    		pubgFinanceFlowDetail.setClubId(pubgMatch.getClubId());
    		pubgFinanceFlowDetail.setClubName(pubgMatch.getClubName());
    		pubgFinanceFlowDetail.setTeamId(pubgMatchSettlement.getTeamId());
    		pubgFinanceFlowDetail.setTeamName(pubgMatchSettlement.getTeamName());
    		pubgFinanceFlowDetail.setInOutFlag(1);
    		pubgFinanceFlowDetail.setTradeMoney(clubProfit);
    		pubgFinanceFlowDetail.setTradeMoneyAfter(pubgClub.getClubBalance() + clubProfit);
    		pubgFinanceFlowDetail.setTradeTypeId(TradeType.MATCH_WIN_ADD.key());
    		pubgFinanceFlowDetail.setTradeTypeName(TradeType.MATCH_WIN_ADD.value());
    		pubgFinanceFlowDetail.setRelationOrderNo(pubgMatch.getRowId() + "_" + pubgMatch.getMatchName());
    		pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
    		this.pubgFinanceFlowDetailService.saveObj(pubgFinanceFlowDetail);
    	} catch (Exception e) {
    		throw new RuntimeException("确认比赛结果出错！", e);
    	}
    }
}
